package com.mojian.controller;

import com.mojian.common.Result;
import com.mojian.model.vo.MemberOrderVO;
import com.mojian.model.vo.MemberPlanVO;
import com.mojian.model.vo.MemberUserVO;
import com.mojian.service.MemberService;
import com.mojian.service.impl.MemberServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员控制器
 */
@RestController
@RequestMapping("/api/member")
@RequiredArgsConstructor
@Api(tags = "会员接口")
@Slf4j
public class MemberController {

    private final MemberService memberService;
    private final JdbcTemplate jdbcTemplate;

    /**
     * 创建会员订单
     */
    @PostMapping("/order/create")
    @ApiOperation("创建会员订单")
    public Result<MemberOrderVO> createMemberOrder(@RequestBody MemberOrderVO orderVO) {
        log.info("创建会员订单: {}", orderVO);
        return memberService.createMemberOrder(orderVO);
    }

    /**
     * 查询会员订单状态
     */
    @GetMapping("/order/status/{orderNo}")
    @ApiOperation("查询会员订单状态")
    public Result<MemberOrderVO> checkOrderStatus(@PathVariable String orderNo) {
        log.info("查询会员订单状态: {}", orderNo);
        // 确保只处理会员订单
        if (orderNo != null && orderNo.startsWith("VIP")) {
            return memberService.checkOrderStatus(orderNo);
        } else {
            log.error("订单号格式不正确，不是有效的会员订单号: {}", orderNo);
            return Result.error("订单号格式不正确，不是有效的会员订单号");
        }
    }

    /**
     * 获取会员套餐列表
     */
    @GetMapping("/plans")
    @ApiOperation("获取会员套餐列表")
    public Result<List<MemberPlanVO>> getMemberPlans() {
        return memberService.getMemberPlans();
    }

    /**
     * 获取当前用户会员信息
     */
    @GetMapping("/info")
    @ApiOperation("获取当前用户会员信息")
    public Result<MemberUserVO> getMemberInfo() {
        return memberService.getCurrentMemberInfo();
    }

    /**
     * 手动重建所有会员权限
     */
    @PostMapping("/rebuild-access")
    @ApiOperation("手动重建所有会员权限")
    public Result<String> rebuildMemberAccess() {
        try {
            // 直接调用 MemberServiceImpl 中的重建方法
            MemberServiceImpl memberServiceImpl = (MemberServiceImpl) memberService;
            memberServiceImpl.rebuildAllMemberArticleAccess();
            return Result.success("会员权限重建成功");
        } catch (Exception e) {
            log.error("重建会员权限失败", e);
            return Result.error("重建会员权限失败: " + e.getMessage());
        }
    }

    /**
     * 确保存在会员专享文章
     */
    @PostMapping("/ensure-member-articles")
    @ApiOperation("确保存在会员专享文章")
    public Result<Map<String, Object>> ensureMemberArticles() {
        log.info("检查并确保系统中存在会员专享文章");
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 检查是否有会员专享文章
            Integer memberArticleCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_article WHERE read_type = 2", Integer.class);
            result.put("memberArticleCountBefore", memberArticleCount);
            
            log.info("系统中共有{}篇会员专享文章", memberArticleCount);
            
            if (memberArticleCount == null || memberArticleCount == 0) {
                // 2. 没有会员专享文章，将最近的一篇文章修改为会员专享
                List<Map<String, Object>> recentArticles = jdbcTemplate.queryForList(
                    "SELECT id, title FROM sys_article WHERE status = 1 ORDER BY create_time DESC LIMIT 5");
                result.put("recentArticles", recentArticles);
                
                if (!recentArticles.isEmpty()) {
                    // 将第一篇文章设为会员专享
                    Long articleId = ((Number) recentArticles.get(0).get("id")).longValue();
                    String title = (String) recentArticles.get(0).get("title");
                    
                    // 更新文章类型
                    jdbcTemplate.update(
                        "UPDATE sys_article SET read_type = 2 WHERE id = ?", articleId);
                    
                    log.info("已将文章[{}] - '{}' 设置为会员专享", articleId, title);
                    result.put("updatedArticleId", articleId);
                    result.put("updatedArticleTitle", title);
                    
                    // 重新查询会员专享文章数量
                    memberArticleCount = jdbcTemplate.queryForObject(
                        "SELECT COUNT(*) FROM sys_article WHERE read_type = 2", Integer.class);
                    result.put("memberArticleCountAfter", memberArticleCount);
                    
                    // 3. 创建所有会员对这篇文章的访问权限
                    String memberSql = "SELECT user_id, expire_time FROM member_user WHERE expire_time > NOW()";
                    List<Map<String, Object>> members = jdbcTemplate.queryForList(memberSql);
                    result.put("memberCount", members.size());
                    
                    if (!members.isEmpty()) {
                        // 为每个会员创建访问权限
                        for (Map<String, Object> member : members) {
                            Long userId = ((Number) member.get("user_id")).longValue();
                            Timestamp expireTime = (Timestamp) member.get("expire_time");
                            
                            // 删除可能存在的冲突记录
                            jdbcTemplate.update(
                                "DELETE FROM member_article_access WHERE user_id = ? AND article_id = ?",
                                userId, articleId);
                                
                            // 添加新记录
                            jdbcTemplate.update(
                                "INSERT INTO member_article_access (user_id, article_id, expire_time, create_time) VALUES (?, ?, ?, NOW())",
                                userId, articleId, expireTime);
                                
                            log.info("已为会员[{}]创建文章[{}]的访问权限", userId, articleId);
                        }
                        
                        // 重建所有会员权限
                        MemberServiceImpl memberServiceImpl = (MemberServiceImpl) memberService;
                        memberServiceImpl.rebuildAllMemberArticleAccess();
                        
                        result.put("accessRightsCreated", true);
                    } else {
                        log.warn("系统中没有有效会员，无需创建访问权限记录");
                        result.put("accessRightsCreated", false);
                        result.put("reason", "no active members");
                    }
                } else {
                    result.put("error", "系统中没有可用的文章");
                }
            } else {
                log.info("系统中已有会员专享文章，无需修改");
                
                // 查询会员专享文章列表
                List<Map<String, Object>> memberArticles = jdbcTemplate.queryForList(
                    "SELECT id, title FROM sys_article WHERE read_type = 2");
                result.put("memberArticles", memberArticles);
                
                // 重建所有会员权限
                MemberServiceImpl memberServiceImpl = (MemberServiceImpl) memberService;
                memberServiceImpl.rebuildAllMemberArticleAccess();
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("确保会员专享文章失败", e);
            result.put("error", e.getMessage());
            return Result.error("确保会员专享文章失败: " + e.getMessage());
        }
    }

    /**
     * 检查数据库状态 - 针对用户1813
     */
    @GetMapping("/debug-data/{userId}")
    @ApiOperation("检查数据库状态")
    public Result<Map<String, Object>> debugDatabaseState(@PathVariable Long userId) {
        log.info("检查用户[{}]相关的数据库状态", userId);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 检查会员专享文章(read_type=2)数量
            Integer memberArticleCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_article WHERE read_type = 2", Integer.class);
            result.put("memberArticleCount", memberArticleCount);
            
            if (memberArticleCount > 0) {
                // 获取前5篇会员文章的ID
                List<Map<String, Object>> memberArticles = jdbcTemplate.queryForList(
                    "SELECT id, title FROM sys_article WHERE read_type = 2 LIMIT 5");
                result.put("sampleMemberArticles", memberArticles);
            }
            
            // 2. 检查用户会员状态
            List<Map<String, Object>> memberInfo = jdbcTemplate.queryForList(
                "SELECT * FROM member_user WHERE user_id = ?", userId);
            result.put("memberInfo", memberInfo);
            
            if (!memberInfo.isEmpty()) {
                Map<String, Object> member = memberInfo.get(0);
                LocalDateTime expireTime = ((Timestamp) member.get("expire_time")).toLocalDateTime();
                result.put("isMembershipActive", expireTime.isAfter(LocalDateTime.now()));
                result.put("membershipExpireTime", expireTime);
            }
            
            // 3. 检查用户的会员订单
            List<Map<String, Object>> orders = jdbcTemplate.queryForList(
                "SELECT * FROM member_order WHERE user_id = ? ORDER BY create_time DESC", userId);
            result.put("memberOrders", orders);
            
            // 4. 检查会员文章访问权限记录
            List<Map<String, Object>> accessRecords = jdbcTemplate.queryForList(
                "SELECT * FROM member_article_access WHERE user_id = ?", userId);
            result.put("accessRecords", accessRecords);
            result.put("accessRecordCount", accessRecords.size());
            
            // 5. 检查memberUser和member_article_access表中expire_time是否一致
            if (!memberInfo.isEmpty()) {
                Map<String, Object> member = memberInfo.get(0);
                LocalDateTime memberExpireTime = ((Timestamp) member.get("expire_time")).toLocalDateTime();
                
                // 手动添加会员文章访问权限
                if (accessRecords.isEmpty() && memberArticleCount > 0) {
                    String insertSql = 
                        "INSERT INTO member_article_access (user_id, article_id, expire_time, create_time) " +
                        "SELECT ?, id, ?, NOW() FROM sys_article WHERE read_type = 2";
                    
                    int count = jdbcTemplate.update(insertSql, userId, memberExpireTime);
                    result.put("newlyAddedAccessRecords", count);
                    log.info("为用户[{}]添加了{}条文章访问权限记录", userId, count);
                    
                    // 重新查询访问权限记录
                    accessRecords = jdbcTemplate.queryForList(
                        "SELECT * FROM member_article_access WHERE user_id = ?", userId);
                    result.put("updatedAccessRecords", accessRecords);
                    result.put("updatedAccessRecordCount", accessRecords.size());
                }
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("检查数据库状态失败", e);
            result.put("error", e.getMessage());
            return Result.error("检查数据库状态失败: " + e.getMessage());
        }
    }

    /**
     * 检查并修复用户会员状态
     */
    @PostMapping("/check-and-fix/{userId}")
    @ApiOperation("检查并修复用户会员状态")
    public Result<Map<String, Object>> checkAndFixMemberStatus(@PathVariable Long userId) {
        log.info("开始检查并修复用户[{}]的会员状态", userId);
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 检查用户是否存在会员记录
            String memberSql = "SELECT * FROM member_user WHERE user_id = ?";
            List<Map<String, Object>> memberRecords = jdbcTemplate.queryForList(memberSql, userId);
            
            result.put("hasMemberRecord", !memberRecords.isEmpty());
            if (!memberRecords.isEmpty()) {
                result.put("memberRecord", memberRecords.get(0));
                
                // 2. 检查会员是否有效
                String validSql = "SELECT COUNT(*) FROM member_user WHERE user_id = ? AND expire_time > NOW()";
                Integer validMember = jdbcTemplate.queryForObject(validSql, Integer.class, userId);
                result.put("isValidMember", validMember != null && validMember > 0);
                
                // 3. 检查用户的文章访问权限
                String accessSql = "SELECT COUNT(*) FROM member_article_access WHERE user_id = ?";
                Integer accessCount = jdbcTemplate.queryForObject(accessSql, Integer.class, userId);
                result.put("articleAccessCount", accessCount);
                
                // 4. 如果会员有效但没有访问权限记录，自动修复
                if (validMember != null && validMember > 0 && (accessCount == null || accessCount == 0)) {
                    // 添加所有会员专享文章的访问权限
                    String insertSql = 
                        "INSERT INTO member_article_access (user_id, article_id, expire_time, create_time) " +
                        "SELECT ?, id, (SELECT expire_time FROM member_user WHERE user_id = ?), NOW() " +
                        "FROM sys_article WHERE read_type = 2";
                    
                    int inserted = jdbcTemplate.update(insertSql, userId, userId);
                    result.put("fixedAccessCount", inserted);
                    log.info("已为用户[{}]创建{}条文章访问权限记录", userId, inserted);
                }
            } else {
                // 5. 如果用户没有会员记录，检查是否有成功的支付订单
                String orderSql = 
                    "SELECT * FROM member_order WHERE user_id = ? AND status = 'SUCCESS' " +
                    "ORDER BY pay_time DESC LIMIT 1";
                List<Map<String, Object>> orderRecords = jdbcTemplate.queryForList(orderSql, userId);
                
                result.put("hasSuccessfulOrder", !orderRecords.isEmpty());
                
                if (!orderRecords.isEmpty()) {
                    result.put("latestOrder", orderRecords.get(0));
                    
                    // 获取订单中的days和支付时间
                    Map<String, Object> order = orderRecords.get(0);
                    Integer days = ((Number) order.get("days")).intValue();
                    LocalDateTime payTime = ((Timestamp) order.get("pay_time")).toLocalDateTime();
                    LocalDateTime expireTime = payTime.plusDays(days);
                    
                    // 创建会员记录
                    String insertMemberSql = 
                        "INSERT INTO member_user (user_id, level, start_time, expire_time, create_time, update_time) " +
                        "VALUES (?, ?, ?, ?, NOW(), NOW())";
                    
                    jdbcTemplate.update(insertMemberSql, userId, 1, payTime, expireTime);
                    log.info("已为用户[{}]创建会员记录，有效期至{}", userId, expireTime);
                    result.put("membershipCreated", true);
                    result.put("expireTime", expireTime);
                    
                    // 创建文章访问权限
                    String insertAccessSql = 
                        "INSERT INTO member_article_access (user_id, article_id, expire_time, create_time) " +
                        "SELECT ?, id, ?, NOW() FROM sys_article WHERE read_type = 2";
                    
                    int inserted = jdbcTemplate.update(insertAccessSql, userId, expireTime);
                    result.put("articleAccessCreated", inserted);
                    log.info("已为用户[{}]创建{}条文章访问权限记录", userId, inserted);
                }
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("检查用户会员状态失败", e);
            result.put("error", e.getMessage());
            return Result.error("检查用户会员状态失败: " + e.getMessage());
        }
    }
} 